package com.cangxuan.app.ui.collection;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.Goods;
import com.cangxuan.app.entity.Order;
import com.cangxuan.app.ui.BaseActivity;
import com.cangxuan.app.ui.user.MyOrderActivity;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;

import java.io.File;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

public class OrderPayActivity extends BaseActivity {

    class MyOrderAdapter extends BaseAdapter {

        private List<Order> orderList;

        public MyOrderAdapter(List<Order> orderList) {
            this.orderList = orderList;
        }

        @Override
        public int getCount() {
            return orderList.size();
        }

        @Override
        public Object getItem(int i) {
            return orderList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return orderList.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            MyOrderViewHolder viewHolder;
            if (view == null) {
                view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_order_pay_list_item, viewGroup, false);
                viewHolder = new MyOrderViewHolder(view);
                view.setTag(viewHolder);
            } else {
                viewHolder = (MyOrderViewHolder) view.getTag();
            }

            Order order = JSONObject.parseObject(JSONObject.toJSONString(orderList.get(i)), Order.class);


            String goodsImagePath = "/data/data/" + getApplicationContext().getPackageName() + order.getImage();
            File imageFile = new File(goodsImagePath);
            if (imageFile.exists()) {
                viewHolder.orderListImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
            } else {
                Thread thread = new Thread(() -> {
                    boolean result = HttpUtils.download(order.getImage(), goodsImagePath);
                    if (result) {
                        handler.post(() -> {
                            viewHolder.orderListImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
                        });
                    }
                });
                thread.start();
            }

            viewHolder.orderListName.setText("藏品名称");
            viewHolder.orderListPrice.setText("￥" + order.getPrice());

            //主页
            if (comeFrom == 0) {
                viewHolder.orderListId.setVisibility(View.INVISIBLE);
                viewHolder.orderListCount.setVisibility(View.VISIBLE);
                viewHolder.orderListCount.setText("数量:" + order.getCount());
            } else if (comeFrom == 1) {
                viewHolder.orderListId.setVisibility(View.VISIBLE);
                viewHolder.orderListCount.setVisibility(View.INVISIBLE);
                viewHolder.orderListCount.setText("编号:NO." + order.getId());
            }

            return view;
        }

        /**
         * 视图持有类，
         * 该类的属性会包含ListView的项里面需要动态设置值的控件
         */
        class MyOrderViewHolder {
            ImageView orderListImg;
            TextView orderListName;
            TextView orderListId;
            TextView orderListPrice;
            TextView orderListCount;

            public MyOrderViewHolder(View view) {
                this.orderListImg = view.findViewById(R.id.orderlist_img);
                this.orderListName = view.findViewById(R.id.orderlist_name);
                this.orderListId = view.findViewById(R.id.orderlist_id);
                this.orderListPrice = view.findViewById(R.id.orderlist_price);
                this.orderListCount = view.findViewById(R.id.orderlist_count);
            }

        }

    }

    ListView myOrderListview;
    Handler handler = new Handler();

    TextView sum;
    Button pay;
    LinearLayout payLoading;
    LinearLayout timeTitle;
    TextView lastTime;
    ConstraintLayout payWay;
    Map<String, String> header;
    List<Order> orderLists;
    int comeFrom;

    int topIndex;
    RadioButton btnAmount;
    RadioButton btnFastpay;
    int ck = 0;
    long seconds = 0;
    long minutes = 0;
    Timer timer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_pay);
        setTitle("订单确认");

        myOrderListview = findViewById(R.id.pay_list);
        sum = findViewById(R.id.pay_bottom_sum);
        pay = findViewById(R.id.order_pay);
        payLoading = findViewById(R.id.pay_loading);
        timeTitle = findViewById(R.id.time_title);
        payWay = findViewById(R.id.pay_way);
        lastTime = findViewById(R.id.last_time);
        btnAmount = findViewById(R.id.btn_amount);
        btnFastpay = findViewById(R.id.btn_fastpay);


        payLoading.setVisibility(View.GONE);

        header = new HashMap<>();
        header.put("Authorization", DeviceUtils.getDeviceID());

        Intent intent = getIntent();
        orderLists = new ArrayList<>();
        topIndex = intent.getIntExtra("topIndex", 0);
        comeFrom = intent.getIntExtra("comeFrom", 0);
        if (comeFrom == 0) {
            Order order = JSONObject.parseObject(intent.getStringExtra("orderform"), Order.class);
            orderLists.add(order);
        } else {
            List<Order> order = (List<Order>) intent.getSerializableExtra("orderform");
            orderLists = order;
        }
        Float sums = Float.valueOf(intent.getStringExtra("sum"));


        MyOrderAdapter myOrderAdapter = new MyOrderAdapter(orderLists);
        myOrderListview.setAdapter(myOrderAdapter);
        sum.setText("合计金额: ￥" + sums);
        pay.setOnClickListener(view -> {
            if (comeFrom == 0) {
                createUserGoods();
            } else {
                paySuccessRegistration();
            }
        });

        setPayWay();

        btnAmount.setOnClickListener(view -> {
            if (ck != 0) {
                ck = 0;
                setPayWay();
            }
        });

        btnFastpay.setOnClickListener(view -> {
            if (ck != 1) {
                ck = 1;
                setPayWay();
            }
        });


        LocalDateTime now = LocalDateTime.now();
        Order o = JSONObject.parseObject(JSONObject.toJSONString(orderLists.get(0)), Order.class);
        LocalDateTime end = o.getCreateTime().plus(10, ChronoUnit.MINUTES);

        seconds = Duration.between(now, end).getSeconds()+2;

        setTimeChange();

        if (orderLists.size() == 1) {
            if (topIndex == 0) {
                tryCancelOverTime(orderLists.get(0).getId());
            } else {
                Order order = JSONObject.parseObject(JSONObject.toJSONString(orderLists.get(0)), Order.class);
                tryPayCancelOverTime(order);
            }
        }


    }

    private void setTimeChange() {
        if (timer==null){
            timer = new Timer(false);
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    System.out.println(seconds);
                    if (seconds > 0) {
                        seconds -= 1;
                        minutes = (long) Math.ceil(seconds / 60);
                        String str = String.format("%02d", minutes)+":"+String.format("%02d", seconds - (minutes * 60));
                        handler.post(() -> {
                            lastTime.setText(str);
                        });
                    } else {
                        handler.post(()->{
                            timer.cancel();
                            btnAmount.setEnabled(false);
                            if (comeFrom == 0) {
                                createUserGoods();
                            } else {
                                paySuccessRegistration();
                            }
                        });
                    }

                }
            };
            timer.schedule(timerTask, new Date(), 1000);
        }

    }

    private void setPayWay() {
        if (ck == 0) {
            btnAmount.setChecked(true);
            btnFastpay.setChecked(false);
        } else {
            btnAmount.setChecked(false);
            btnFastpay.setChecked(true);
        }
    }

    private void tryCancelOverTime(int id) {
        setAllVisibility();
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/orderform/overTime/" + id, header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                handler.post(() -> {
                    setAllGone();
                });
            } else {
                handler.post(() -> {
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        });
        thread.start();
    }

    private void tryPayCancelOverTime(Order order) {
        setAllVisibility();
        List<Order> cancelList = new ArrayList<>();
        cancelList.add(order);
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(cancelList));
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.post("/api/registration/overTime/", header, String.valueOf(array));
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                handler.post(() -> {
                    setAllGone();
                });
            } else {
                handler.post(() -> {
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        });
        thread.start();
    }

    private void setAllVisibility() {
        payLoading.setVisibility(View.VISIBLE);
        timeTitle.setVisibility(View.GONE);
        payWay.setVisibility(View.GONE);
        myOrderListview.setVisibility(View.GONE);
    }

    private void setAllGone() {
        payLoading.setVisibility(View.GONE);
        timeTitle.setVisibility(View.VISIBLE);
        payWay.setVisibility(View.VISIBLE);
        myOrderListview.setVisibility(View.VISIBLE);
    }


    private void createUserGoods() {
        setAllVisibility();
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/orderform/successPay/" + orderLists.get(0).getId(), header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                handler.post(() -> {
                    setAllGone();
                    finish();
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            } else {
                handler.post(() -> {
                    setAllGone();
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        });
        thread.start();
    }


    private void paySuccessRegistration() {
        setAllVisibility();
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(orderLists));
        System.out.println(array);
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.post("/api/registration/pay", header, String.valueOf(array));
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                handler.post(() -> {
                    setAllGone();
                    finish();
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            } else {
                handler.post(() -> {
                    setAllGone();
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        });
        thread.start();
    }

    @Override
    public void onBackPressed() {
        createBackDialog();

    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            createBackDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void createBackDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("是否返回上个界面，如果是订单请在我的订单页面进行查看")
                .setPositiveButton("是", (dialog, which) -> {
                    finish();
                })
                .setNegativeButton("否", (dialog, which) -> {

                }).setCancelable(false).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
    }
}
